import cls from 'cls-hooked';
import _ from 'lodash';

import models from './models/';

const env = process.env.NODE_ENV || 'development';

const config = require('./config/')[env];
import { Sequelize } from 'sequelize-typescript';

Sequelize.useCLS(cls.createNamespace('p2m-sequelize-transition'));

class DateBase {
  private sequelize: any;

  public init(callback: any) {
    if (config.database) {
      this.connect().then(callback || _.noop);
    }
  }

  private connect(): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.sequelize = new Sequelize({
        ...config,
        models: Object.values(models || {}),
      });
      this.sequelize
        .authenticate()
        .then(() => {
          console.log('Connection has been established successfully.');
          resolve();
        })
        .catch((err: any) => {
          console.error('Unable to connect to the database:', err);
          reject();
        });
    })
  }

}

const db = new DateBase();

export default db;
